package com.k.kc.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MapUtil {
    public static String convertToKvString(Map<String, String> paramsMap) {
        return paramsMap.entrySet().stream()
                .map(itm ->
                {
                    try {
                        return itm.getKey() + "=" + URLEncoder.encode(String.valueOf(itm.getValue()), "UTF-8");
                    } catch (Exception e) {
                        throw new RuntimeException("URL Encode exception", e);
                    }
                })
                .collect(Collectors.joining("&"));
    }

    public static String convertToQueryString(String uriStr, Map<String, String> paramsMap) {
        URI uri = URI.create(uriStr);
        String query = uri.getQuery();
        String connectDelimiter = (query == null || query.trim().length() == 0) ? "?" : "&";
        uriStr = uri + connectDelimiter + convertToKvString(paramsMap);
        return uriStr;
    }

    public static String convertToJsonString(Map<String,Object> paramsMap){
        String leftHuakuohao = "{";
        String rightHuakuohao = "}";
        String yinHao = "\"";
        String body =  paramsMap.entrySet().stream()
                .map(itm ->
                {
                    try {
                        return
                                yinHao+itm.getKey()+yinHao + ":" + yinHao+ URLEncoder.encode(String.valueOf(itm.getValue()), "UTF-8")+yinHao
                                ;
                    } catch (Exception e) {
                        throw new RuntimeException("URL Encode exception", e);
                    }
                })
                .collect(Collectors.joining(","));
        return leftHuakuohao + body + rightHuakuohao;
    }

    public static void main(String[] args) throws JsonProcessingException {
        Map<String,Object> map = new HashMap<>();
        map.put("id","a1101");
        map.put("name","tom");
        String json = MapUtil.convertToJsonString(map);
        System.out.println(json);
        ObjectMapper objectMapper = new ObjectMapper();
        String json1 = objectMapper.writeValueAsString(map);
        System.out.println(json1);

    }
}
